<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bpmBizTitle"
                    placeholder="请输入标题"
                    :max-length="255"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="离职人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep :multi="false" v-model="model.employeeId" disabled></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="人员编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeNo">
                  <a-input v-model="model.employeeNo" placeholder="请输入人员编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所在部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departmentId">
                  <j-select-depart v-model="model.departmentId" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input v-model="model.teamId" :tdlx="3" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workUnit">
                  <select-Company-input placeholder="请选择所属公司" :disabled="formDisabled" v-model="model.workUnit" />
                </a-form-model-item>
              </a-col>

              <!-- <a-col :span="8">
                <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input :disabled="formDisabled" v-model="model.teamId" :tdlx="3" disabled/>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="岗位名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="positionId">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.positionId"
                    dictCode="sys_position,name,id"
                    placeholder="请选择岗位名称"
                    disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="入职日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryTime">
                  <j-date placeholder="请选择入职日期" v-model="model.entryTime" style="width: 100%" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同到期日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractTime">
                  <j-date placeholder="请选择合同到期日期" v-model="model.contractTime" style="width: 100%" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="员工类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeType">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.employeeType"
                    dictCode="employee_type"
                    placeholder="请选择员工类别"
                    disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="离职类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="resignType">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.resignType"
                    dictCode="resign_type"
                    placeholder="请选择离职类型" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="离职原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="resignReason">
                  <a-textarea
                    :disabled="formDisabled"
                    v-model="model.resignReason"
                    rows="4"
                    placeholder="请输入离职原因"
                    :max-length="500" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea
                    :disabled="formDisabled"
                    v-model="model.remark"
                    rows="4"
                    placeholder="请输入备注"
                    :max-length="500" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="评价信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="离职日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="resignTime">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择离职日期"
                    v-model="model.resignTime"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="薪资截止日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salaryEndDate">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择薪资截止日期"
                    v-model="model.salaryEndDate"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="社保截止日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="socialSecurityDeadline">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择社保截止日期"
                    v-model="model.socialSecurityDeadline"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="公积金截止日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="accumulationFundDate">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择公积金截止日期"
                    v-model="model.accumulationFundDate"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="资产/物品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="assets">
                  <a-input :disabled="formDisabled" v-model="model.assets" placeholder="请输入资产/物品"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="借款/次数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="loanMoney">
                  <a-input :disabled="formDisabled" v-model="model.loanMoney" placeholder="请输入借款/次数"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="工作交接" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workHandover">
                  <select-user-by-dep
                    :disabled="formDisabled"
                    :multi="false"
                    v-model="model.workHandover"></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="档案资料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="profiles">
                  <a-input :disabled="formDisabled" v-model="model.profiles" placeholder="请输入档案资料"></a-input>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item
                  label="培训扣款（元）"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="trainingDeduction">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.trainingDeduction"
                    placeholder="请输入培训扣款"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item
                  label="电脑扣款（元）"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="computerDeduction">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.computerDeduction"
                    placeholder="请输入电脑扣款"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="其他扣款（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherDeduction">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.otherDeduction"
                    placeholder="请输入其他扣款"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col> -->
            </a-row>
            <a-row :gutter="48">
              <a-col :span="24">
                <p style="color:rgba(0, 0, 0, 0.85)">培训扣款(元):</p>
                <ErpEmployeeTrainingList ref="trainingRef" :employeeId="model.employeeId" :resignTime="model.resignTime"></ErpEmployeeTrainingList>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload :disabled="formDisabled" v-model="model.attachment"></j-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list
        v-if="formBpm && model.bpmStatus !== '1'"
        :formData="formData"
        style="margin-top: 10px"></common-flow-list>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button
          type="primary"
          v-if="formBpm"
          :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }"
          @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <process-config-modal ref="processConfig" @ok="handleSuccess" @close="handleClose"></process-config-modal>
    <ErpHrEmployeeResignBillFormPrint
      v-if="formBpm"
      id="resignContent"
      class="print_style"
      :formData="model"
      :formDataHistory="formData"></ErpHrEmployeeResignBillFormPrint>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import { mapGetters } from 'vuex';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpHrEmployeeResignBillFormPrint from './ErpHrEmployeeResignBillFormPrint'
import ErpEmployeeTrainingList from './reference/ErpEmployeeTrainingList'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
export default {
  name: 'ErpHrEmployeeResignBillForm',
  components: {
    SelectUserByDep,
    SelectTeamInput,
    ProcessConfigModal,
    CommonFlowList,
    ErpHrEmployeeResignBillFormPrint,
    SelectCompanyInput,
    ErpEmployeeTrainingList
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      activeKey: ['1', '2', '3'],
      model: {
        billNo: null
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        teamId: [
          { required: true, message: '请选择所属团队!' }
        ],
        workUnit: [
          { required: true, message: '请选择所属公司!' }
        ],
        bpmBizTitle: [
          { required: true, message: '请输入流程标题!' }
        ],
        resignType: [
          { required: true, message: '请选择离职类型!' }
        ],
        resignReason: [
          { required: true, message: '请输入离职原因!' }
        ],
        resignTime: [
          { required: true, message: '请选择离职日期!' }
        ],
        salaryEndDate: [
          { required: true, message: '请选择薪资截止日期!' }
        ],
        socialSecurityDeadline: [
          { required: true, message: '请选择社保截止日期!' }
        ],
        accumulationFundDate: [
          { required: true, message: '请选择社公积金截止日期!' }
        ],
        assets: [
          { required: true, message: '请输入资产/物品!' }
        ],
        loanMoney: [
          { required: true, message: '请输入借款/次数!' }
        ],
        workHandover: [
          { required: true, message: '请选择工作交接人!' }
        ],
        profiles: [
          { required: true, message: '请输入档案资料!' }
        ],
        // trainingDeduction: [
        //   { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的培训扣款!' }
        // ],
        computerDeduction: [
          { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的电脑扣款!' }
        ],
        otherDeduction: [
          { required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的其他扣款!' }
        ]
      },
      url: {
        startProcess: '/api/erpmng/act/process/extActProcess/startMutilProcess',
        generatedFormNumber: '/api/erp/base/generatedFormNumber',
        add: '/api/erp/hr/resign/erpHrEmployeeResignBill/add',
        edit: '/api/erp/hr/resign/erpHrEmployeeResignBill/edit',
        queryById: '/api/erp/hr/resign/erpHrEmployeeResignBill/queryById',
        queryContractByEmployeeId: '/api/erp/hr/contract/erpHrEmployeeContract/queryByEmployeeId',
        queryPostRecordByInfo: '/api/erp/files/employee/erpEmployeePostChangeRecord/queryPostRecordByInfo',
        addTrainingList: '/api/erp/files/employee/erpEmployeeTraining/list',
        detailTrainingList: '/api/erp/files/employee/erpEmployeeTrainingResign/list'

      },
       // 代码生成后需手动设置流程编码
      flowCode: 'onl_erp_hr_employee_resign_bill',
      formUrl: 'erp/hr/resign/modules/ErpHrEmployeeResignBillForm',
      formUrlMobile: '/pages/synergy/erpHrEmployeeResignBillForm',
      processId: '1540236705217404929',
      beanName: 'erpHrEmployeeResignBillServiceImpl'
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    ...mapGetters(['userInfo']),
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'LZSQ', subSystemCode: '02' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'billNo', res.result)
          this.$set(this.modelDefault, 'billNo', res.result);
        }
      })
    },
    add() {
      let that = this;
      let userinfo = this.userInfo();
      this.generatedFormNumber();
      this.$set(this.modelDefault, 'employeeId', userinfo.empId);
      this.$set(this.modelDefault, 'applyId', userinfo.employee.applyId);
      this.$set(this.modelDefault, 'employeeNo', userinfo.employee.employeeNo);
      // this.$set(this.modelDefault, 'workUnit', userinfo.employee.rogDepart);
      this.$set(this.modelDefault, 'departmentId', userinfo.deptId);
     // this.$set(this.modelDefault,'teamId',userinfo.employee.teamId);
      // this.$set(this.modelDefault,'positionId',userinfo.employee.mainPost);
      this.$set(this.modelDefault, 'entryTime', userinfo.employee.joinDate);
      this.$set(this.modelDefault, 'employeeType', userinfo.employee.employeeType);
      this.$set(this.modelDefault, 'bpmBizTitle', userinfo.employee.name);
      this.$nextTick(() => {
        this.$refs.trainingRef.url.list = this.formDisabled ? this.url.detailTrainingList : this.url.addTrainingList
        // this.$refs.trainingRef.mainId = ''
        this.$refs.trainingRef.loadData()
      })
      getAction(this.url.queryContractByEmployeeId, { employeeId: userinfo.empId }).then(res => {
        if (res.success) {
          let data = res.result;
          if (data) {
            if (data[0]) {
              this.$set(this.modelDefault, 'contractTime', data[0].endDate);
            } else {
              that.$message.warning('您暂无员工合同！');
            }
            this.edit(this.modelDefault)
          }
        }
      });
      getAction(this.url.queryPostRecordByInfo, { employeeId: userinfo.empId, departId: userinfo.deptId }).then(res => {
        if (res.success) {
          let data = res.result;
          if (data) {
            this.$set(this.modelDefault, 'teamId', data[0].teamId);
            this.$set(this.modelDefault, 'positionId', data[0].postId);
            this.edit(this.modelDefault)
          }
        }
      })
    },
    edit(record) {
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
        this.$nextTick(() => {
          this.$refs.trainingRef.url.list = this.formDisabled ? this.url.detailTrainingList : this.url.addTrainingList
          this.$refs.trainingRef.mainId = this.model.id
          this.$refs.trainingRef.loadData()
        })
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    handleSuccess() {
      this.$emit('ok', 'refresh');
    },
    handleClose () {
      this.$emit('close');
    },
    // 发起流程
    startProcess: function (id) {
      let record = { id: id };
      this.$refs.processConfig.visible = true
      this.$refs.processConfig.formUrl = this.formUrl
      this.$refs.processConfig.formUrlMobile = this.formUrlMobile
      this.$refs.processConfig.flowCode = this.flowCode
      this.$refs.processConfig.edit(record, '', this.beanName);
      // var that = this;
      // var param = {
      //   flowCode: that.flowCode,
      //   id: id,
      //   formUrl: that.formUrl,
      //   formUrlMobile: that.formUrlMobile
      // }
      // postAction(that.url.startProcess, param).then((res) => {
      //   if (res.success) {
      //     that.$message.success(res.message);
      //     that.$emit('ok');
      //   } else {
      //     that.$message.warning(res.message);
      //   }
      // }).catch((e) => {
      //   this.$message.warning('不识别的请求!');
      // });
    },
    // 保存草稿
    submitTempForm() {
      // fix:BUG#5030 离职申请单-退回流程，再次提交后，数据携带问题 start
      if (!this.model.otherDeduction) {
        this.$set(this.model, 'otherDeduction', 0)
      }
      this.$set(this.model, 'employeeTrainingList', this.$refs.trainingRef.dataSource)
      // 计算培训扣款
      if (this.$refs.trainingRef.dataSource && this.$refs.trainingRef.dataSource.length > 0) {
        let total = 0
        this.$refs.trainingRef.dataSource.forEach((item, index) => {
          total += Number(item.remainingDeductions) || 0
        })
        this.$set(this.model, 'trainingDeduction', total.toFixed(2))
      } else {
        this.$set(this.model, 'trainingDeduction', 0)
      }
      // fix:BUG#5030 离职申请单-退回流程，再次提交后，数据携带问题 end
      const that = this
      // 触发表单验证
      let httpurl = ''
      let method = ''
      if (!this.model.id) {
        httpurl += this.url.add
        method = 'post'
      } else {
        httpurl += this.url.edit
        method = 'put'
      }
      httpAction(httpurl, this.model, method)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok', 'draft', that.model);
          } else {
            that.$message.warning(res.message)
            that.$emit('unButtonDisable');
          }
        }).catch(err => {
          that.$emit('unButtonDisable', err);
        })
        .finally(() => {
        })
    },
    submitForm(type) {
      if (type && type == 'draft') {
        this.submitTempForm()
        return false
      }
      // fix:BUG#5030 离职申请单-退回流程，再次提交后，数据携带问题 start
      if (!this.model.otherDeduction) {
        this.$set(this.model, 'otherDeduction', 0)
      }
      this.$set(this.model, 'employeeTrainingList', this.$refs.trainingRef.dataSource)
      // 计算培训扣款
      if (this.$refs.trainingRef.dataSource && this.$refs.trainingRef.dataSource.length > 0) {
        let total = 0
        this.$refs.trainingRef.dataSource.forEach((item, index) => {
          total += Number(item.remainingDeductions) || 0
        })
        this.$set(this.model, 'trainingDeduction', total.toFixed(2))
      } else {
        this.$set(this.model, 'trainingDeduction', 0)
      }
      // fix:BUG#5030 离职申请单-退回流程，再次提交后，数据携带问题 end
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                let data = res.result;
                if (this.model.id) {
                //  that.$message.success(res.message)
                  this.startProcess(this.model.id);
                } else {
                //  that.$message.success(res.message)
                  this.startProcess(data);
                  this.model.id = data;
                }
              } else {
                that.$message.warning(res.message)
                that.$emit('unButtonDisable');
              }
            }).catch(err => {
              that.$emit('unButtonDisable', err);
            })
            .finally(() => {
              that.confirmLoading = false
            })
        } else {
          that.$emit('unButtonDisable');
        }
      })
    },

    // 点击打印
    onPrint () {
      let print = new Print({
        el: '#resignContent',
        popTitle: '离职申请详情 · 禾美环保',
        endCallback() {

        }
      })
    }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
</style>
